#include "CCMainWindow.h"
#include "WindowManager.h"
#include <QSqlQuery>
#include "CommonUtils.h"

QString gstrLoginHeadPath;
QString gLoginEmployeeID;

CCMainWindow::CCMainWindow(QWidget *parent)
    : BasicWindow(parent)
    , ui(new Ui::CCMainWindowClass())
{
    ui->setupUi(this);

	setWindowFlags(Qt::WindowType::Tool | windowFlags());
	loadStyleSheet("CCMainWindow");

	QSqlQuery query;
	QString sql = QString(
		"UPDATE tab_employees SET online = 2 WHERE employeeID = (			\
			SELECT employeeID FROM tab_accounts WHERE account = '%1'	\
		)"
	).arg(userA);
	query.exec(sql);

	initControl();
	initTimer();
	
}


void CCMainWindow::initTimer()
{
	QTimer *timer = new QTimer(this);
	timer->setInterval(1000);

	connect(timer, &QTimer::timeout, [this]()
	{
		static int count = 10;
		if (count > 99) count = 0;

		this->setLevelPixmap(count++);
	});

	timer->start();
}

void CCMainWindow::initControl()
{
	ui->treeWidget->setStyle(new CustomProxyStyle(this));

	QSqlQuery query;
	const QString &sql = QString(
		"SELECT employee_name, employee_sign, status, picture, online, employeeID\
		FROM tab_employees\
		WHERE employeeID = (\
			SELECT employeeID\
			FROM tab_accounts\
			WHERE account = '%1'\
			); "
	).arg(userA);
	query.exec(sql);
	query.next();

	//const QString &employee_name, employee_sign, status, picture, online;
	const QString &employee_name = query.value(0).toString();
	const QString &employee_sign = query.value(1).toString();
	const int &status = query.value(2).toInt();
	const QString &picture = query.value(3).toString();
	const int &online = query.value(4).toInt();
	gLoginEmployeeID = query.value(5).toString();

	setLevelPixmap(0);
	setHeadPixmap(picture);
	gstrLoginHeadPath = picture;
	setStatusMenuIcon(":/Resources/MainWindow/StatusSucceeded.png");
	setUserName(employee_name);
	ui->lineEdit->setText(employee_sign);

	QHBoxLayout *layout = new QHBoxLayout(ui->appWidget);
	layout->setContentsMargins(0, 0, 0, 0);
	layout->addWidget(addOtherAppExtension(":/Resources/MainWindow/app/app_10.png", app_10));
	layout->addWidget(addOtherAppExtension(":/Resources/MainWindow/app/app_2.png", app_2));
	layout->addWidget(addOtherAppExtension(":/Resources/MainWindow/app/skin.png", skin));
	layout->addWidget(addOtherAppExtension(":/Resources/MainWindow/app/app_4.png", app_4));
	layout->addWidget(addOtherAppExtension(":/Resources/MainWindow/app/app_5.png", app_5));
	layout->addStretch();
	layout->setSpacing(2);

	ui->bottomLayout_up->addWidget(addOtherAppExtension(":/Resources/MainWindow/app/app_3.png", app_1));
	ui->bottomLayout_up->addWidget(addOtherAppExtension(":/Resources/MainWindow/app/app_6.png", app_6));
	ui->bottomLayout_up->addWidget(addOtherAppExtension(":/Resources/MainWindow/app/app_7.png", app_7));
	ui->bottomLayout_up->addWidget(addOtherAppExtension(":/Resources/MainWindow/app/app_8.png", app_8));
	ui->bottomLayout_up->addWidget(addOtherAppExtension(":/Resources/MainWindow/app/app_9.png", app_9));
	ui->bottomLayout_up->addStretch();

	connect(ui->sysmin, SIGNAL(clicked(bool)), this, SLOT(onShowHide(bool)));
	connect(ui->sysclose, SIGNAL(clicked(bool)), this, SLOT(onShowQuit(bool)));
	connect(ui->sysclose, SIGNAL(clicked(bool)), this, SLOT(onShowQuit(bool)));

	SysTray *systemTrayIcon = new SysTray(this);

	ui->searchBtn->installEventFilter(this);
	ui->searchLineEdit->installEventFilter(this);

	connect(NotifyManager::getInstance(), &NotifyManager::signalSkinChanged,
		[this](QColor color)->void {
			this->ui->searchWidget->setStyleSheet(QString("\
				QWidget#searchWidget{\
					background-color:rgba(%1,%2,%3,80);\
				}\
				QPushButton#searchBtn{\
					border-image:url(:/Resources/MainWindow/search/search_icon.png)\
				}\
			")
			.arg(color.red())
			.arg(color.green())
			.arg(color.blue()));
	});

	initContactTree();
}

void CCMainWindow::setUserName(const QString & username)
{
	ui->userName->adjustSize();


	QString name = ui->userName->fontMetrics().elidedText(
		username, 
		Qt::TextElideMode::ElideRight,
		ui->userName->width()
	);

	ui->userName->setText(name);
}

void CCMainWindow::setLevelPixmap(int level)
{
	QPixmap pixmap(ui->levenBtn->size());
	pixmap.fill(Qt::GlobalColor::transparent);

	QPainter painter(&pixmap);

	painter.drawPixmap(0, 4, QPixmap(":/Resources/MainWindow/lv.png"));

	painter.drawPixmap(10, 4, QPixmap(":/Resources/MainWindow/levelvalue.png"),
		6 * (level / 10), 0, 6, 7);
	painter.drawPixmap(16, 4, QPixmap(":/Resources/MainWindow/levelvalue.png"),
		6 * (level % 10), 0, 6, 7);

	ui->levenBtn->setIcon(pixmap);
}

void CCMainWindow::setStatusMenuIcon(const QString & path)
{
	QPixmap pixmap(ui->stausBtn->size());
	pixmap.fill(Qt::GlobalColor::transparent);

	QPainter painter(&pixmap);
	painter.drawPixmap(4, 4, QPixmap(path));

	ui->stausBtn->setIcon(pixmap);
	ui->stausBtn->setIconSize(ui->stausBtn->size());
}

void CCMainWindow::setHeadPixmap(const QString & path)
{
	ui->headLabel->setPixmap(
		getRoundImage(QPixmap(path), 
		QPixmap(":/Resources/MainWindow/head_mask.png"),
		ui->headLabel->size())
	);
}

QWidget* CCMainWindow::addOtherAppExtension(const QString & appPath, APP_NAME appName)
{
	QPushButton *btn = new QPushButton(this);
	btn->setFixedSize(20, 20);

	QPixmap pixmap(btn->size());
	pixmap.fill(Qt::GlobalColor::transparent);

	QPainter painter(&pixmap);
	QPixmap appPixmap(appPath);
	painter.drawPixmap(
		(btn->width() - appPixmap.width()) / 2, 
		(btn->height() - appPixmap.height()) / 2,
		appPixmap
	);

	btn->setIcon(pixmap);
	btn->setIconSize(btn->size());
	btn->setProperty("hasborder", true);
	//btn->setObjectName();
	switch(appName) {
	case APP_NAME::app_1:
		btn->setObjectName("app_1");
		break;
	case APP_NAME::app_2:
		btn->setObjectName("app_2");
		break;
	case APP_NAME::app_3:
		btn->setObjectName("app_3");
		break;
	case APP_NAME::app_4:
		btn->setObjectName("app_4");
		break;
	case APP_NAME::app_5:
		btn->setObjectName("app_5");
		break;
	case APP_NAME::app_6:
		btn->setObjectName("app_6");
		break;
	case APP_NAME::app_7:
		btn->setObjectName("app_7");
		break;
	case APP_NAME::app_8:
		btn->setObjectName("app_8");
		break;
	case APP_NAME::app_9:
		btn->setObjectName("app_9");
		break;
	case APP_NAME::app_10:
		btn->setObjectName("app_10");
		break;
	case APP_NAME::app_11:
		btn->setObjectName("app_11");
		break;
	case APP_NAME::skin:
		btn->setObjectName("skin");
		connect(btn, SIGNAL(clicked()), this, SLOT(onSkinAppIconClicked()));
		break;
	case APP_NAME::face_setting_btn_normal:
		break;
	default:
		;
	};
	return btn;
}

bool CCMainWindow::eventFilter(QObject * watched, QEvent * event)
{
	if (watched == ui->searchLineEdit) {
		if (event->type() == QEvent::FocusIn) {
			ui->searchWidget->setStyleSheet(QString("\
				QWidget#searchWidget{\
					background-color:rgb(255,255,255);\
					border-bottom:1px solid rgba(%1,%2,%3,50)\
				}\
				QPushButton#searchBtn{\
					border-image:url(:/Resources/MainWindow/search/main_search_deldown.png)\
				}\
				QPushButton#searchBtn:hover{\
					border-image:url(:/Resources/MainWindow/search/main_search_delhighlight.png)\
				}\
				QPushButton#searchBtn:pressed{\
					border-image:url(:/Resources/MainWindow/search/main_search_delhighdown.png)\
				}\
			")
				.arg(m_colorBackGround.red())
				.arg(m_colorBackGround.green())
				.arg(m_colorBackGround.blue()));

		}
		else if(event->type() == QEvent::FocusOut)
		{
			ui->searchWidget->setStyleSheet(QString("\
				QWidget#searchWidget{\
					background-color:rgba(%1,%2,%3,80);\
				}\
				QPushButton#searchBtn{\
					border-image:url(:/Resources/MainWindow/search/search_icon.png)\
				}\
			")
				.arg(m_colorBackGround.red())
				.arg(m_colorBackGround.green())
				.arg(m_colorBackGround.blue()));
		}
	}
	return BasicWindow::eventFilter(watched, event);
}

void CCMainWindow::resizeEvent(QResizeEvent * event)
{
	//setUserName(QString::fromLocal8Bit("超级工程机加工"));
	//setUserName(QString::fromUtf8("超级工程机加工"));

	return BasicWindow::resizeEvent(event);
}

void CCMainWindow::mousePressEvent(QMouseEvent * event)
{
	if (qApp->widgetAt(event->pos()) != ui->lineEdit 
		&&
		ui->lineEdit->hasFocus())
	{
		ui->lineEdit->clearFocus();
	}

	if (qApp->widgetAt(event->pos()) != ui->searchLineEdit
		&&
		ui->searchLineEdit->hasFocus())
	{
		ui->searchLineEdit->clearFocus();
	}

	__super::mousePressEvent(event);
}

void CCMainWindow::onItemClicked(QTreeWidgetItem *item, int column)
{
	bool bIsChild = item->data(0, Qt::UserRole).toBool();
	if (!bIsChild)
	{
		item->setExpanded(!item->isExpanded());
		//item->setExpanded(true);
	}

}

void CCMainWindow::onItemDoubleClicked(QTreeWidgetItem *item, int column)
{
	bool k = item->data(0, Qt::UserRole).toBool();

	if (k)
	{
		WindowManager::getInstance()->addNewTalkWindow(
			item->data(0, Qt::UserRole + 1).toString()
		);


		/*int s = m_groupMap.value(item);

		if (s == QString("一一"))
		{
			WindowManager::getInstance()->addNewTalkWindow(
				item->data(0, Qt::UserRole + 1).toString(),
				GroupType::COMPANY
			);
		}
		else if (s == QString("一二"))
		{
			WindowManager::getInstance()->addNewTalkWindow(
				item->data(0, Qt::UserRole + 1).toString(),
				GroupType::PERSONELGROUP
			);
		}
		else if (s == QString("一三"))
		{
			WindowManager::getInstance()->addNewTalkWindow(
				item->data(0, Qt::UserRole + 1).toString(),
				GroupType::DEVELOPMENTGROUP
			);
		}
		else if (s == QString("一四"))
		{
			WindowManager::getInstance()->addNewTalkWindow(
				item->data(0, Qt::UserRole + 1).toString(),
				GroupType::MARKETGROUP
			);
		}
		else if (s == QString("一五"))
		{
			WindowManager::getInstance()->addNewTalkWindow(
				item->data(0, Qt::UserRole + 1).toString(),
				GroupType::PTOP
			);
		}
		else
		{
			WindowManager::getInstance()->addNewTalkWindow(
				item->data(0, Qt::UserRole + 1).toString(),
				GroupType::USER
			);
		}*/

	}
}

void CCMainWindow::onItemExpanded(QTreeWidgetItem * item)
{
	bool bIsChild = item->data(0, Qt::UserRole).toBool();

	if (!bIsChild) 
	{
		RootcontactItem *rootItem = qobject_cast<RootcontactItem*>(ui->treeWidget->itemWidget(item, 0));
		
		rootItem->setExpanded(true);
	}

}

void CCMainWindow::onItemCollapsed(QTreeWidgetItem * item)
{
	bool bIsChild = item->data(0, Qt::UserRole).toBool();

	if (!bIsChild)
	{
		RootcontactItem *rootItem = qobject_cast<RootcontactItem*>(ui->treeWidget->itemWidget(item, 0));

		rootItem->setExpanded(false);
	}
}

void CCMainWindow::initContactTree()
{	
	ui->treeWidget->setRootIsDecorated(false);
	ui->treeWidget->setIndentation(10);
	//void itemClicked(QTreeWidgetItem *item, int column);
	//void itemDoubleClicked(QTreeWidgetItem *item, int column);
	connect(ui->treeWidget, SIGNAL(itemClicked(QTreeWidgetItem*, int)),
		this, SLOT(onItemClicked(QTreeWidgetItem*, int)));
	connect(ui->treeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)),
		this, SLOT(onItemDoubleClicked(QTreeWidgetItem*, int)));

	//void itemExpanded(QTreeWidgetItem *item);
	//void itemCollapsed(QTreeWidgetItem *item);
	connect(ui->treeWidget, SIGNAL(itemExpanded(QTreeWidgetItem*)),
		this, SLOT(onItemExpanded(QTreeWidgetItem*)));
	connect(ui->treeWidget, SIGNAL(itemCollapsed(QTreeWidgetItem*)),
		this, SLOT(onItemCollapsed(QTreeWidgetItem*)));

	//ui->treeWidget->set

	QTreeWidgetItem *pRootGroupItem = new QTreeWidgetItem;
	pRootGroupItem->setChildIndicatorPolicy(QTreeWidgetItem::ChildIndicatorPolicy::ShowIndicator);
	pRootGroupItem->setData(0, Qt::UserRole, 0);

	RootcontactItem *pItem = new RootcontactItem(true, ui->treeWidget);
	pItem->setText("一二三四五六");

	ui->treeWidget->addTopLevelItem(pRootGroupItem);
	ui->treeWidget->setItemWidget(pRootGroupItem, 0, pItem);

	QSqlQuery query;
	QString sql = QString(
		"SELECT departmentID FROM tab_employees WHERE employeeID = (SELECT employeeID FROM tab_accounts WHERE account = '%1') ;"
	).arg(userA);
	query.exec(sql);
	query.next();

	QList<int> contactList;
	contactList << 2000; contactList << query.value(0).toInt(); 
	

	for (int i = 0; i < contactList.size(); i++) {
		addCompanyDeps(pRootGroupItem, contactList.at(i));
	}

	
}

void CCMainWindow::addCompanyDeps(QTreeWidgetItem * pRootGroupItem, const int & sDeps)
{
	QSqlQuery query;
	query.exec(
		QString(
			"SELECT department_name, picture, sign FROM tab_department WHERE departmentID=%1;"
		).arg(sDeps)
	);
	query.next();
	const QString &sDepsSql = query.value(0).toString();
	const QString &picture = query.value(1).toString();
	const QString &sign = query.value(2).toString();

	QTreeWidgetItem *pChild = new QTreeWidgetItem;
	pChild->setData(0, Qt::UserRole, 1);
	pChild->setData(0, 
		Qt::UserRole+1, 
		sDeps
		);

	pRootGroupItem->addChild(pChild);

	ContactItem *childItem = new ContactItem(ui->treeWidget);
	childItem->setUserName(sDepsSql);
	childItem->setSignName(sign);
	childItem->setHeadPixmap(
		/*getRoundImage(
			QPixmap(picture),
			QPixmap(":/Resources/MainWindow/head_mask.png"),
			childItem->getHeadLabelSize()
		)*/
		CommonUtils::getRoundImage(
			QPixmap(picture),
			QPixmap(":/Resources/MainWindow/head_mask.png"),
			childItem->getHeadLabelSize()
		)
	);
	
	ui->treeWidget->setItemWidget(pChild, 0, childItem);


	m_groupMap.insert(pChild, sDeps);
}

void CCMainWindow::onSkinAppIconClicked()
{
	//获取信号发送人
	if (sender()->objectName() == "skin")
	{

	}

	SkinWidget * skin = new SkinWidget;
	skin->show();
}

CCMainWindow::~CCMainWindow()
{	


	delete ui;
}

void CCMainWindow::onShowQuit(bool)
{
	QSqlQuery query;
	QString sql = QString(
		"UPDATE tab_employees SET online = 1 WHERE employeeID = (			\
			SELECT employeeID FROM tab_accounts WHERE account = '%1'	\
		)"
	).arg(userA);
	query.exec(sql);

	BasicWindow::onShowQuit(true);
}
